/**
 * Created Date: Tuesday, October 24th 2023, 12:18:12 am
 * Author: CodingGorit
 * -----
 * Last Modified: Tue Oct 24 2023
 * Modified By: CodingGorit
 * -----
 * Copyright © 2019 —— 2023 fmin-courses TP Center All Rights Reserved
 * ------------------------------------
 * Javascript will save your soul!
 */

import { ColumnProps, ImageProps, UserProps } from "@/types";
import columnJpg from '@/assets/img/column.jpg';
import avatarJpg from '@/assets/img/avatar.jpg';

export function generateFitUrl(data: ImageProps, width: number, height: number, format = ['m_pad']) {
    if (data && data.url) {
        const formatStr = format.reduce((prev, current) => {
            return current + ',' + prev
        }, '')
        data.fitUrl = data.url + `?x-oss-process=image/resize,${formatStr}h_${height},w_${width}`
    }
}

export function addColumnAvatar(data: ColumnProps | UserProps, width: number, height: number) {
    if (data.avatar) {
      generateFitUrl(data.avatar, width, height)
    } else {
      const parseCol = data as ColumnProps
      data.avatar = {
        fitUrl: parseCol.title ? columnJpg : avatarJpg
      }
    }
  }

interface CheckCondition {
    format?: string[];
    size?: number;
}

type ErrorType = 'size' | 'format' | null;

export function beforeUploadCheck(file: File, condition: CheckCondition) {
    const { format, size } = condition;
    const isValidFormat = format ? format.includes(file.type) : true;
    const isValidSize = size ? file.size < size * 1024 * 1024 : true;
    let error: ErrorType = null;
    if (!isValidFormat) {
        error = 'format';
    }
    if (!isValidSize) {
        error = 'size';
    }
    return {
        passed: isValidFormat && isValidSize,
        error: error
    }
}